<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Requests\Admin\LoginRequest;
use App\Model\Admin;
use App\Model\Settings;
use App\Http\Controllers\Common\CommonController;

/**
 * @author LiYongHeng <[616649679@qq.com]>
 * @date   2017-9-21
 */
class LoginController extends Controller
{
    /**
     * 加载后台登录页面
     * @return [object] 执行加载模板
     */
    public function login()
    {
        //查询是否开启验证码设置
        $set = Settings::select('adminCode')->first();
        $adminCode = $set->adminCode;
        return view('Admin/Login/login', ['adminCode' => $adminCode]);
    }

    /**
     * 处理登录验证
     * @param  login  $request [登录请求验证]
     * @return json       [返回状态码与信息]
     */
    public function doLogin(LoginRequest $request)
    {
        //查询是否开启验证码
        $set = Settings::select('adminCode')->first();
        // 赋值传入数据
        $username = $request->input('username');
        $pwd = $request->input('pwd');
        $code = $request->input('code');
        // 如果开启验证码设置判断输入验证码是否正确
        if ($set->adminCode == 1) {
            if ($code != session('code')) {
                return response()->json([
                'code' => 1403,
                'msg' => '验证码错误',
                ]);
            }
        }
        // 查询登录用户
        $mod = Admin::select('id','username','pwd', 'power')
            ->where([
            ['username', $username],
            ['state', 1],
            ]) ->first();
        // 判断是否存在此用户
        if (!$mod) {
            return response()->json([
                'code' => 1401,
                'msg' => '用户名不存在或密码错误',
                ]);
        }
        // 判断是否密码正确
        if (!password_verify($pwd, $mod->pwd)) {
            return response()->json([
                'code' => 1402,
                'msg' => '用户名不存在或密码错误',
                ]);
        }
        // 实例化公共函数文件
        $common = new CommonController;
        // 记录登入行为到后台日志
        $common->admin_log($mod->username, 1, "登入后台");
        session(['adminUser' => ["username"=>$mod->username,'power'=>$mod->power,'id'=>$mod->id]]);

        // 返回响应成功json
        return response()->json([
                'code' => 2000,
                'msg' => '登录成功',
            ]);

    }

    /**
     * [logout 注销]
     * @param  Request $request [请求数据]
     * @return [object]           [返回重定向路径页面]
     */
     public function logout(Request $request)
     {
        // 实例化公共函数文件
        $common = new CommonController;
        // 记录注销行为到后台日志
        $common->admin_log(session('adminUser')['username'], 7, "退出登录");
        // 注销session
        $request->session()->forget('adminUser');
        $request->session()->forget('adminPower');

        return redirect('admin/login');
     }
}
